package com.example.blog.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.blog.domain.Permission;
import com.example.blog.domain.Users;
import com.example.blog.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

//编写自定义的认证逻辑，也就是密码比对的逻辑
@Service
public class MyDetailService implements UserDetailsService {
    //编写逻辑
   @Autowired
   public UsersMapper usersMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//       1.构造查询条件
        //根据字段名username 进行比对
        QueryWrapper<Users> wrapper = new QueryWrapper<Users>().eq("username",username);
//       2.查询用户
           Users users = usersMapper.selectOne(wrapper);

           if(users==null){
               return  null;
           }
        // 3.查询用户权限,根据用户名·查询权限
        List<Permission> permissions = usersMapper.findPermissionByAccount(username);
        // 4.将自定义权限集合转为Security的权限类型集合
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Permission permission : permissions) {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
        }
//       3.封装为UserDetails对象
      UserDetails userDetails =  User.withUsername(users.getUsername())
                //查询的密码
                .password(users.getPassword())
                //查询的权限
                .authorities(grantedAuthorities)
                .build();
        return userDetails;
    }
}
